#encoding=utf8
'''
Created on Apr 3, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.contrib import admin
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.db import transaction

import settings
from utils import field
from app_info.models import AppleID, FlurryKey, GAKey, QuantCastKey, App
from appleid_info.models import EmptyModel
from django.utils import timezone
from app_info.forms import FlurryKeyForm, AppleIDForm, GAKeyForm, QuantCastKeyForm
from django.core.exceptions import PermissionDenied

csrf_protect_m = method_decorator(csrf_protect)


class AppleIDAdmin(admin.ModelAdmin):
    list_per_page = 20
    search_fields = ('app__prj_code', 'request_id')
    list_display = ('request_id', 'get_status', 'get_app', 'get_studio', 'itunes_id',
        'get_editor', 'added_at')
    list_filter = ('status',)
    readonly_fields = ('request_id', 'app', 'get_app')
    change_list_template = 'changelist.html'
    change_form_template = 'changeform.html'
    form = AppleIDForm
    fieldsets = (
        (None, {
            'fields':
            (
            'request_id',
            'get_app',
            'itunes_id',
            'added_at',
            'status',
            ),
        }),
    )

    @field('Fulfilled by', admin_order_field='editor')
    def get_editor(self, obj):
        return obj.editor.split('@')[0]

    @field('Status', allow_tags=True, admin_order_field='status')
    def get_status(self, obj):
        return obj.get_status_mark()

    @field('App', allow_tags=True, admin_order_field='app__prj_code')
    def get_app(self, obj):
        return "<a href='%s%s/' target='_blank'>%s</a>" % ('/admin/app_info/app/',
            obj.app_id, obj.app)

    @field('Studio', admin_order_field='app__studio__pub_name')
    def get_studio(self, obj):
        return obj.app.studio

    def has_add_permission(self, request):
        return False

    def get_actions(self, request):
        """
        remove delete action
        """
        actions = super(AppleIDAdmin, self).get_actions(request)
        if actions.get('delete_selected'):
            del actions['delete_selected']
        return actions

    def save_model(self, request, obj, form, change):
        if 'itunes_id' in form.changed_data:
            obj.app.store_link = 'https://itunes.apple.com/app/id%s?mt=8' %\
            obj.itunes_id if obj.itunes_id else ""
            obj.app.app_id = obj.itunes_id if obj.itunes_id else ""
            obj.app.save()
            obj.editor = request.user.email
            if not obj.added_at:
                obj.added_at = timezone.now()
        obj.save()

    def changelist_view(self, request, extra_context=None):
        extra_context = {'app_label': settings.APP_LABEL_LOCAL.get('appleid_info')}
        return admin.ModelAdmin.changelist_view(self, request, extra_context=extra_context)

    @csrf_protect_m
    @transaction.commit_on_success
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = {'app_label': settings.APP_LABEL_LOCAL.get('appleid_info')}
        return admin.ModelAdmin.change_view(self, request, object_id, form_url=form_url, extra_context=extra_context)


class FlurryKeyAdmin(admin.ModelAdmin):
    list_per_page = 20
    search_fields = ('app__prj_code', 'request_id')
    list_display = ('request_id', 'get_status', 'get_app', 'get_coordinator', 'get_studio', 'key',
        'get_editor', 'added_at')
    list_filter = ('status',)
    readonly_fields = ('request_id', 'get_app', 'app')
    change_list_template = 'changelist.html'
    change_form_template = 'changeform.html'
    form = FlurryKeyForm

    def get_fieldsets(self, request, obj=None):
        return (
            (None, {
                'fields':
                (
                    'request_id',
                    'get_app',
                    'key',
                    'added_at',
                    'status',
                ),
            }),
        )

    @field('Coordinator')
    def get_coordinator(self, obj):
        v1 = obj.app.appversion_set.filter(code='1.0')
        return v1[0].get_coordinator() if v1 else ''

    @field('Fulfilled by', admin_order_field='editor')
    def get_editor(self, obj):
        return obj.editor.split('@')[0]

    @field('Status', allow_tags=True, admin_order_field='status')
    def get_status(self, obj):
        return obj.get_status_mark()

    @field('App', allow_tags=True, admin_order_field='app__prj_code')
    def get_app(self, obj):
        return "<a href='%s%s/' target='_blank'>%s - %s</a>" % ('/admin/app_info/app/',
            obj.app_id, obj.app.prj_code, obj.app.app_name)

    @field('Studio', admin_order_field='app__studio__pub_name')
    def get_studio(self, obj):
        return obj.app.studio

    def get_actions(self, request):
        actions = admin.ModelAdmin.get_actions(self, request)
        if actions.get('delete_selected'):
            del actions['delete_selected']
        return actions

    def has_add_permission(self, request):
        return False

    def changelist_view(self, request, extra_context=None):
        extra_context = {'app_label': settings.APP_LABEL_LOCAL.get('appleid_info')}
        return admin.ModelAdmin.changelist_view(self, request, extra_context=extra_context)

    @csrf_protect_m
    @transaction.commit_on_success
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = {'app_label': settings.APP_LABEL_LOCAL.get('appleid_info')}
        user = request.user
        if user.groups.filter(name='Management').exists() and not user.is_superuser:
            raise PermissionDenied
        return admin.ModelAdmin.change_view(self, request, object_id, form_url=form_url, extra_context=extra_context)

    def save_model(self, request, obj, form, change):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        if not obj:
            num = FlurryKey.objects.get_latest_num()
            obj.request_id = 'RFLU-%s%02i%02i%02i' % (current_year, current_month, current_day, num)
        if 'key' in form.changed_data:
            obj.app.flurry_key = obj.key or ""
            obj.app.save()
            obj.editor = request.user.email
            if not obj.added_at:
                obj.added_at = timezone.now()
            if obj.status == 'S':
                obj.status = 'R'
        if 'status' in form.changed_data:
            if obj.status == 'C':
                obj.app.flurry_key = ""
                obj.app.save()
            if obj.status == 'R':
                obj.app.flurry_key = obj.key
                obj.app.save()
        obj.save()


class GAKeyAdmin(FlurryKeyAdmin):
    form = GAKeyForm
    raw_id_fields = ('app', )

    def get_fieldsets(self, request, obj=None):
        if not obj:
            return (
                (None, {
                    'fields':
                    (
                        'app',
                        'status',
                    ),
                }),
            )
        return (
            (None, {
                'fields':
                (
                    'request_id',
                    'get_app',
                    'key',
                    'added_at',
                    'status',
                ),
            }),
        )

    class Media:
        js = ('base/js/appleid_info_admin.js', 'base/js/RelatedObjectLookups.js')

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('request_id', 'app', 'get_app')
        return ('request_id', 'get_app', 'key', 'added_at', 'status')

    def has_add_permission(self, request):
        return True

    def save_model(self, request, obj, form, change):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        num = GAKey.objects.get_latest_num()
        if not obj.request_id:
            obj.request_id = 'RGAP-%s%02i%02i%02i' % (current_year, current_month, current_day, num)
            obj.app = form.cleaned_data.get('app')
            obj.save()
        if 'key' in form.changed_data:
            print obj.id, obj.editor, obj.added_at, obj.status
            obj.app.ga_key = obj.key or ""
            obj.app.save()
            obj.editor = request.user.email
            if not obj.added_at:
                obj.added_at = timezone.now()
            if obj.status == 'S':
                obj.status = 'R'
        if 'status' in form.changed_data:
            if obj.status == 'C':
                obj.app.ga_key = ""
                obj.app.save()
            if obj.status == 'R':
                obj.app.ga_key = obj.key
                obj.app.save()
        obj.save()


class QuantCastKeyAdmin(FlurryKeyAdmin):
    form = QuantCastKeyForm
    raw_id_fields = ('app', )

    def get_fieldsets(self, request, obj=None):
        if not obj:
            return (
                (None, {
                    'fields':
                    (
                        'app',
                        'status',
                    ),
                }),
            )
        return (
            (None, {
                'fields':
                (
                    'request_id',
                    'get_app',
                    'key',
                    'added_at',
                    'status',
                ),
            }),
        )

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('request_id', 'app', 'get_app')
        return ('request_id', 'get_app', 'key', 'added_at', 'status')

    class Media:
        js = ('base/js/appleid_info_admin.js', 'base/js/RelatedObjectLookups.js')

    def has_add_permission(self, request):
        return True

    def save_model(self, request, obj, form, change):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        num = QuantCastKey.objects.get_latest_num()
        if 'app' in form.changed_data:
            obj.request_id = 'RQUA-%s%02i%02i%02i' % (current_year, current_month, current_day, num)
            obj.app = form.cleaned_data.get('app')
            obj.save()
        if 'key' in form.changed_data:
            obj.app.quantcast_key = obj.key or ""
            obj.app.save()
            obj.editor = request.user.email
            if not obj.added_at:
                obj.added_at = timezone.now()
            if obj.status == 'S':
                obj.status = 'R'
        if 'status' in form.changed_data:
            if obj.status == 'C':
                obj.app.quantcast_key = ""
                obj.app.save()
            if obj.status == 'R':
                obj.app.quantcast_key = obj.key
                obj.app.save()
        obj.save()


#admin.site.register(AppleID, AppleIDAdmin)
admin.site.register(QuantCastKey, QuantCastKeyAdmin)
admin.site.register(GAKey, GAKeyAdmin)
admin.site.register(FlurryKey, FlurryKeyAdmin)
admin.site.register(EmptyModel)
